from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse

from app01 import models
# Create your views here.


def addbook(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        price=request.POST.get('price')
        pub_date = request.POST.get('pub_date')
        press = request.POST.get('press')
        models.Book.objects.create(title=title,press=press,price=price,pub_date=pub_date)
        return redirect(reverse('app01:addbook'))
    return render(request,'addbook.html')

def book_list(request):
    books = models.Book.objects.all()
    return render(request,'bookList.html',{'books':books})

def book_delete(request,id):
    models.Book.objects.filter(id=id).delete()
    return redirect(reverse('app01:booklist'))

def book_change(request,id):
    if request.method=="POST":
        title = request.POST.get('title')
        price = request.POST.get('price')
        pub_date = request.POST.get( 'pub_date')
        press = request.POST.get('press')
        b = models.Book.objects.filter(id=id).update(title=title,press=press,price=price,pub_date=pub_date)
        return redirect((reverse('app01:booklist')))
    else:
        book = models.Book.objects.filter(id=id)[0]
        return render(request,'bookchange.html',{'book':book})